<template>
  <div class="audit-page">
    <el-card>
      <h2 class="title">📝 文章审核与管理</h2>

      <el-table
        :data="posts"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'approved' ? 'success'
                     : scope.row.status === 'pending' ? 'warning'
                     : scope.row.status === 'rejected' ? 'danger'
                     : 'info'"
            >
              {{ statusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="260">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showContent(scope.row)">
              查看内容
            </el-button>

            <el-button
              size="small"
              type="success"
              v-if="scope.row.status === 'pending'"
              @click="approvePost(scope.row.id)"
            >
              审核通过
            </el-button>

            <el-button
              size="small"
              type="danger"
              v-if="scope.row.status === 'approved'"
              @click="rejectPost(scope.row.id)"
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 内容弹窗 -->
    <el-dialog v-model="dialogVisible" title="文章内容" width="50%">
      <h3>{{ selectedPost.title }}</h3>
      <p style="white-space: pre-wrap; line-height: 1.6">{{ selectedPost.content }}</p>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

const posts = ref([]);
const loading = ref(false);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

const dialogVisible = ref(false);
const selectedPost = ref({});

const fetchPosts = async (page = 1) => {
  loading.value = true;
  try {
    const res = await request.get("/api/posts/admin/list", {
      params: { page, pageSize: pageSize.value },
    });
    console.log("📄 管理员帖子列表:", res);
    if (res.code === 200) {
      posts.value = res.data.records || res.data;
      total.value = res.data.total || res.data.length;
    } else {
      ElMessage.error(res.message || "加载失败");
    }
  } catch (err) {
    console.error("加载失败:", err);
    ElMessage.error("权限不足或未登录");
  } finally {
    loading.value = false;
  }
};

const approvePost = async (id) => {
  try {
    await ElMessageBox.confirm("确认要通过这篇文章的审核吗？", "审核确认", {
      type: "warning",
    });
    const res = await request.post(`/api/posts/approve/${id}`);
    if (res.code === 200) {
      ElMessage.success("审核通过");
      fetchPosts(currentPage.value);
    } else {
      ElMessage.warning(res.message);
    }
  } catch (e) {
    if (e !== "cancel") ElMessage.error("操作失败");
  }
};

const rejectPost = async (id) => {
  try {
    await ElMessageBox.confirm("确定要下架该文章吗？", "下架确认", {
      type: "warning",
    });
    const res = await request.post(`/api/posts/reject/${id}`);
    if (res.code === 200) {
      ElMessage.success("已下架该文章");
      fetchPosts(currentPage.value);
    } else {
      ElMessage.warning(res.message);
    }
  } catch (e) {
    if (e !== "cancel") ElMessage.error("操作失败");
  }
};

const showContent = (post) => {
  selectedPost.value = post;
  dialogVisible.value = true;
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchPosts(page);
};

const statusLabel = (status) => {
  switch (status) {
    case "pending": return "待审核";
    case "approved": return "已通过";
    case "rejected": return "已下架";
    default: return "未知";
  }
};

onMounted(() => fetchPosts());
</script>

<style scoped>
.audit-page {
  padding: 30px;
}

.title {
  font-weight: 600;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
